package mybaidu

import (
	"data/config"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"public/mycache"
	"public/mydraw"
	"public/mylog"
	"public/tools"
	"strings"
	"time"
)

/*
	获取百度sdk accesstoken
*/
func OnGetAccessToken() string {
	//获取
	cache := mycache.OnGetCache("baidu_")
	var tp interface{}
	tp, ret := cache.Value("accesstoken")
	if ret {
		return tp.(string)
	}

	accesstoken := getBaiduAccessToken()
	if len(accesstoken) > 0 {
		cache.Add("accesstoken", accesstoken, 24*time.Hour) //24小时超时时间s
	}
	return accesstoken

}

//获取身份证信息
func GetIdCardInfo(dir string) (info BaiduResInfo) {
	access_token := OnGetAccessToken()
	www := "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=" + access_token

	ff, _ := ioutil.ReadFile(dir) //我还是喜欢用这个快速读文件
	img_base64 := base64.StdEncoding.EncodeToString(ff)

	postValues := url.Values{}
	postValues.Set("detect_direction", "true")
	postValues.Set("id_card_side", "front")
	postValues.Set("image", img_base64)

	httpClient := http.Client{}
	httpReq, _ := http.NewRequest("POST", www, strings.NewReader(postValues.Encode()))
	httpReq.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
	httpResp, _ := httpClient.Do(httpReq)
	body, _ := ioutil.ReadAll(httpResp.Body)
	defer httpResp.Body.Close()
	fmt.Println(string(body))

	json.Unmarshal(body, &info)
	return
}

func getBaiduAccessToken() string {
	k, v := config.GetBaiduInfo()
	url := "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + k + "&client_secret=" + v
	httpClient := http.Client{}
	httpReq, _ := http.NewRequest("GET", url, nil)
	httpResp, err := httpClient.Do(httpReq)
	if err != nil {
		mylog.Error(err)
		return ""
	}
	defer httpResp.Body.Close()
	body, _ := ioutil.ReadAll(httpResp.Body)

	stb := BaiduToken{}
	json.Unmarshal(body, &stb)
	return stb.Access_token
}

//保存文件
func OnSaveIdCard(info BaiduResInfo) string {
	return SaveIdCard(
		info.Words_result.IDCard.Words,
		info.Words_result.Name.Words,
		info.Words_result.Sex.Words,
		info.Words_result.Nation.Words,
		info.Words_result.Addr.Words,
		info.Words_result.Birth.Words)
}

//保存文件
func GetIdCard(IDCard, Name, Sex, Nation, Addr, Birth string) string {
	if !tools.CheckFileIsExist(tools.GetCurrentDirectory() + "/file/idcard/" + IDCard + ".png") {
		return SaveIdCard(IDCard, Name, Sex, Nation, Addr, Birth)
	}

	return config.Url_host + config.File_host + "/idcard/" + IDCard + ".png"
}

//保存文件
func SaveIdCard(IDCard, Name, Sex, Nation, Addr, Birth string) string {
	var _dir = ""
	pen, b := mydraw.OnGetPen("./luximr.ttf", 0, 0, 0, 255)
	if b {
		var hdc mydraw.HDC
		hdc.SetBg("./src.png")
		pen.Dpi = 200
		pen.FontSize = 16
		pen.StartPoint.X = 150
		pen.StartPoint.Y = 78
		hdc.DrawText(pen, Name)
		pen.FontSize = 12
		pen.StartPoint.X = 150
		pen.StartPoint.Y = 160
		hdc.DrawText(pen, Sex)
		pen.StartPoint.X = 350
		pen.StartPoint.Y = 160
		hdc.DrawText(pen, Nation)

		var birth = Birth
		if len(birth) < 8 {
			birth = "19700101"
		}
		pen.StartPoint.X = 150
		pen.StartPoint.Y = 240
		hdc.DrawText(pen, birth[0:4])
		pen.StartPoint.X = 290
		pen.StartPoint.Y = 240
		hdc.DrawText(pen, birth[4:6])
		pen.StartPoint.X = 370
		pen.StartPoint.Y = 240
		hdc.DrawText(pen, birth[6:])

		pen.StartPoint.X = 150
		pen.StartPoint.Y = 275

		str := []rune(Addr)
		//str := "北京市海淀区西北旺东路100号中关村科技园"

		for i := 0; i < len(str); i += 11 {
			var end = i + 11
			if end > len(str) {
				end = len(str)
			}
			pen.StartPoint.Y += 40
			tmp := str[i:end]
			hdc.DrawText(pen, string(tmp))
		}

		pen.StartPoint.X = 300
		pen.StartPoint.Y = 520
		hdc.DrawText(pen, IDCard)
		_path := tools.GetCurrentDirectory() + "/file/idcard/"
		tools.BuildDir(_path)
		_dir = config.Url_host + config.File_host + "/idcard/" + IDCard + ".png"
		b = hdc.Save(_path + IDCard + ".png")
	}
	return _dir
}
